﻿using Common;
using DataLibrary;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
//using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Web.Mvc;


namespace ImageWeb.Controllers
{
    [AdminAuthorize]
    public class HomeController : Controller
    {
        private ImageManagerEntities ime = new ImageManagerEntities();
        private static int resultCnt = 0;
        private static IEnumerable<ImageInfo> listR;
        private static string strParam;
        private static IEnumerable<ImageInfo> lastSerachList;
        private static List<string> lastDownloadList = null;
        public ActionResult Index()
        {
            var _workshops = ime.Workshops.AsQueryable().Select(u => new { u.WorkshopID, u.Name }).OrderBy(u=>u.Name).ToList();
            System.Collections.Generic.List<SelectListItem> _listWorkshops = new System.Collections.Generic.List<SelectListItem>(_workshops.Count());
            _listWorkshops.Add(new SelectListItem() { Text = "--请选择--", Value = "" });
            foreach (var workshop in _workshops)
            {
                _listWorkshops.Add(new SelectListItem() { Text = workshop.Name, Value = workshop.WorkshopID.ToString() });
            }
            var _teams = ime.Teams.AsQueryable().Select(u => new { u.TeamID, u.TeamName }).ToList();
            System.Collections.Generic.List<SelectListItem> _listTeams = new System.Collections.Generic.List<SelectListItem>(_teams.Count());
            _listTeams.Add(new SelectListItem() { Text = "--请选择--", Value = "" });
            foreach (var team in _teams)
            {
                _listTeams.Add(new SelectListItem() { Text = team.TeamName, Value = team.TeamID.ToString() });
            }
            ViewData["workshops"] = _listWorkshops;
            ViewData["teams"] = _listTeams;
            ViewData["workshops_e"] = _listWorkshops;
            ViewData["teams_e"] = _listTeams;
            return View();
        }

        public ActionResult getMachine(int workshopid)
        {
            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                Formatting = Formatting.None
            };
            var _machines = ime.Machines.AsQueryable().Select(u => new { u.MachineNum, u.MachineID, u.WorkshopID }).Where(u => u.WorkshopID == workshopid);
            var ret = JsonConvert.SerializeObject(_machines.ToList(), setting);//看着有点麻烦，但貌似这样前端渲染的时间比较快            
            return Json(new { total = _machines.Count(), rows = ret }, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 检索结果
        /// </summary>
        /// <param name="workshopName"></param>
        /// <param name="machineid"></param>
        /// <param name="teamid"></param>
        /// <param name="qualityid"></param>
        /// <param name="boxnum"></param>
        /// <param name="timespan"></param>
        /// <param name="sns"></param>
        /// <param name="pageindex"></param>
        /// <param name="pageSize"></param>
        /// <param name="twice">是否为二次检索</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult getResult(string workshopName, int? machineid, int? teamid, int? qualityid, string boxnum, string timespan, string sns, int? pageindex, int? pageSize, int twice)
        {
            strParam = string.Empty;
            var _where = LinqKit.PredicateBuilder.New<ImageInfo>(true);
            if (!string.IsNullOrEmpty(workshopName) && workshopName != "--请选择--")
            {
                strParam += workshopName;
                _where = _where.And(u => u.ImagePath.Contains(workshopName));
            }
            if (machineid != null)
            {
                strParam += machineid.ToString();
                _where = _where.And(u => u.MachineID == machineid);
            }
            if (teamid != null)
            {
                strParam += teamid.ToString();
                _where = _where.And(u => u.TeamID == teamid);
            }
            if (qualityid != null)
            {
                strParam += qualityid.ToString();
                _where = _where.And(u => u.QualityID == qualityid);
            }

            if (!string.IsNullOrEmpty(timespan))
            {
                strParam += timespan;
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\s-\s");
                if (regex.IsMatch(timespan))
                {
                    timespan = regex.Replace(timespan, "|");
                    string[] parts = timespan.Split('|');
                    DateTime start = DateTime.Parse(parts[0]);
                    DateTime end = DateTime.Parse(parts[1]);
                    _where = _where.And(u => u.Created_at >= start && u.Created_at <= end);
                }
            }
            if (!string.IsNullOrEmpty(sns))
            {
                strParam += sns;
                List<string> snlist = null;
                if (sns.Contains('-'))
                {
                    string[] tmp = sns.Split('-');
                    string start = tmp[0];
                    string end = tmp[1];
                    int len = 0;
                    if (end.Length == start.Length)
                    {
                        //什么都不做
                    }
                    else if (end.Length == 5)
                    {
                        end = start.Substring(0, start.Length - 5) + end;
                    }
                    else
                    {
                        return Json(new { count = -1, ret = "序列号格式错误" });
                    }
                    len = (int)(double.Parse(end) - double.Parse(start) + 1);
                    snlist = new List<string>(len);
                    for (int i = 0; i < len; i++)
                    {
                        string sn = (double.Parse(start) + i).ToString();
                        //_where = _where.Or(u => u.OriginPath == sn);
                        snlist.Add(sn);
                    }
                }
                else
                {
                    string[] snParts = null;
                    if (sns.Contains(','))
                        snParts = sns.Split(',');
                    else if (sns.Contains('\r'))
                        snParts = sns.Split('\r');
                    else if (sns.Contains('\n'))
                        snParts = sns.Split('\n');
                    else
                    {
                        sns = sns + ",";
                        snParts = sns.Split(',');
                    }
                    snlist = new List<string>(snParts.Count());
                    foreach (string sn in snParts)
                    {
                        snlist.Add(sn);
                        //    _where = _where.Or(u => u.OriginPath == sn);
                    }
                }
                _where = _where.And(u => snlist.Contains(u.OriginPath));

            }

            if (pageindex == null)
                pageindex = 0;
            if (pageSize == null)
                pageSize = 12;
            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                Formatting = Formatting.None
            };
            IEnumerable<ImageInfo> result = null;
            List<ImageInfo> images = null;
            string ret = string.Empty;

            if (twice == 1)
            {
                result = listR.AsQueryable().Where(_where.Compile());
            }
            else
            {
                ime.Configuration.LazyLoadingEnabled = false;//延时加载开关，关闭后可以避免查询关联的表数据，其实可以用select来避免这种情况
                if (string.IsNullOrEmpty(strParam))
                {
                    result = ime.ImageInfo.AsQueryable().Take(1000);
                }
                else
                    result = ime.ImageInfo.AsQueryable().Where(_where.Compile());
            }
            listR = result;
            images = result.Skip((int)pageindex).Take((int)pageSize).ToList();
            ret = JsonConvert.SerializeObject(images, setting);

            ImageList(images);
            if (pageindex == 0)
            {
                resultCnt = result.Count();
            }
            return Json(new { count = resultCnt, ret = ret });
        }

        [HttpPost]
        public ActionResult EditImage(int imageid, int? qualityid, int? machineid, int? teamid, int? workshopid, string quality, string machineNum, string teamName, string workshopName)
        {
            string info = "";
            int code = 0;
            var image = ime.ImageInfo.Find(imageid);
            try
            {
                if (image != null)
                {
                    string name = image.ImageName;
                    string[] parts = name.Split('-');
                    string newName = string.Format("{0}-{1}-{2}-{3}-{4}-{5}", parts[0], qualityid == null ? parts[1] : quality, workshopid == null ? parts[2] : workshopName, teamid == null ? parts[3] : teamName, machineid == null ? parts[4] : machineNum, parts[5]);
                    string path = image.ImagePath;
                    string[] parts2 = path.Split('\\');
                    string newPath = string.Format("{0}\\{1}\\{2}\\{3}\\{4}\\{5}\\{6}\\{7}\\{8}", parts2[0], parts2[2], (qualityid == null ? parts2[3] : quality), parts2[4], parts2[5], (workshopid == null ? parts2[6] : workshopName), (teamid == null ? parts2[7] : teamName), (machineid == null ? parts2[8] : machineNum), newName);
                    FileInfo fi = new FileInfo(path);
                    if (!Directory.Exists(Path.GetDirectoryName(newPath)))
                        Directory.CreateDirectory(Path.GetDirectoryName(newPath));
                    fi.MoveTo(newPath);
                    image.ImageName = newName;
                    image.ImagePath = newPath;
                    if (qualityid != null)
                        image.QualityID = (int)qualityid;
                    if (machineid != null)
                        image.MachineID = (int)machineid;
                    if (teamid != null)
                        image.TeamID = (int)teamid;
                    ime.SaveChanges();
                    info = "图片修改成功";
                    code = 1;
                }
                else
                {
                    info = "未找到图片,可能已被删除！";
                    code = 2;
                }
            }
            catch (Exception ex)
            {
                info = ex.Message;
                code = 2;
            }
            return Json(new { code = code, info = info });
        }

        /// <summary>
        /// 批量修改
        /// </summary>     
        [HttpPost]
        public ActionResult EditImageRange(int? qualityid, int? machineid, int? teamid, int? workshopid, string quality, string machineNum, string teamName, string workshopName)
        {
            string info = "";
            int code = 1;
            if (RedisHelper.Get<string>("EditRange" + Session["UserID"]) != null)
            {
                int EditRange = int.Parse(RedisHelper.Get<string>("EditRange" + Session["UserID"]));//每天的初始编辑量是100，在登录时设定好
                if (EditRange < 1)
                {
                    info = "当天批量编辑量已用完，每天最多批量编辑100张图片";
                    code = 2;
                }
                else if (EditRange < listR.Count())
                {
                    info = "每天最多批量编辑100张图片，您还剩" + EditRange + "张图可编辑";
                    code = 2;
                }
                else
                {
                    if (listR.Count() > 0 && listR.Count() <= EditRange)
                    {
                        try
                        {
                            foreach (var item in listR)
                            {
                                var image = ime.ImageInfo.Find(item.ImageID);
                                var name = item.ImageName;
                                string[] parts = name.Split('-');
                                string newName = string.Format("{0}-{1}-{2}-{3}-{4}-{5}", parts[0], qualityid == null ? parts[1] : quality, workshopid == null ? parts[2] : workshopName, teamid == null ? parts[3] : teamName, machineid == null ? parts[4] : machineNum, parts[5]);
                                string path = image.ImagePath;
                                string[] parts2 = path.Split('\\');
                                string newPath = string.Format("{0}\\{1}\\{2}\\{3}\\{4}\\{5}\\{6}\\{7}\\{8}", parts2[0], parts2[1], (qualityid == null ? parts2[2] : quality), parts2[3], parts2[4], (workshopid == null ? parts2[5] : workshopName), (teamid == null ? parts2[6] : teamName), (machineid == null ? parts2[7] : machineNum), newName);
                                FileInfo fi = new FileInfo(path);
                                if (!Directory.Exists(Path.GetDirectoryName(newPath)))
                                    Directory.CreateDirectory(Path.GetDirectoryName(newPath));
                                if (fi.Exists)
                                    fi.MoveTo(newPath);
                                image.ImageName = newName;
                                image.ImagePath = newPath;
                                if (qualityid != null)
                                    image.QualityID = (int)qualityid;
                                if (machineid != null)
                                    image.MachineID = (int)machineid;
                                if (teamid != null)
                                    image.TeamID = (int)teamid;
                                ime.SaveChanges();
                            }
                            int leftRange = EditRange - listR.Count();//剩余下载量
                            RedisHelper.Set<string>("EditRange" + Session["UserID"], leftRange.ToString(), DateTime.Now.AddDays(1) - DateTime.Now);
                            info = "批量修改成功";
                            code = 1;
                        }
                        catch (Exception ex)
                        {
                            info = ex.Message;
                            code = 2;
                        }
                    }
                }
            }
            return Json(new { code = code, info = info });

        }

        [HttpPost]
        public ActionResult DeleteImage(int imageid)
        {
            string info = "";
            int code = 0;
            var image = ime.ImageInfo.Find(imageid);
            try
            {
                if (image != null)
                {
                    ime.ImageInfo.Remove(image);
                    ime.SaveChanges();
                    DeleteImage(image.ImagePath);
                    info = "图片删除成功";
                    code = 1;
                }
                else
                {
                    info = "未找到图片,可能已被删除！";
                    code = 2;
                }
            }
            catch (Exception ex)
            {
                info = ex.Message;
                code = 0;
            }
            return Json(new { code = code, info = info });
        }

        public ActionResult Logout()
        {
            int userid = int.Parse(Session["UserID"].ToString());
            RedisHelper.DelKey("web" + userid.ToString());
            Session.Clear();
            return RedirectToAction("Login", "Login"); ;
        }

        [HttpPost]
        public ActionResult Download(int flag, string workshopName, int? machineid, int? teamid, int? qualityid, string boxnum, string timespan, string sns)
        {          
            if (listR != null && flag == 1)
            {
                if (lastSerachList != null && lastSerachList == listR && lastDownloadList != null)
                {
                    return Json(new { total = lastDownloadList.Count(), info = lastDownloadList });
                }
                List<string> filelist = new List<string>();
                List<string> downloadList = new List<string>();
                string imagePath = "";
                string download = "";
                int cnt = 1;
                if (listR.Count() <= 500)
                {                    
                    foreach (var item in listR.ToList())
                    {
                        // string filePath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Images"), item.ImageName);
                        string filePath = item.ImagePath;
                        if (System.IO.File.Exists(filePath))
                            filelist.Add(filePath);
                        if (filelist.Count() % 100 == 0 && filelist.Count() > 0)
                        {
                            imagePath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Images"), string.Format("{0}-{1}.zip", DateTime.Now.ToString("yyyyMMddHHmmssffff"), cnt));
                            ZipUtility.Zipfiles(filelist, imagePath);
                            filelist.Clear();
                            download = Path.Combine(Request.ApplicationPath + "Images/", Path.GetFileName(imagePath));
                            downloadList.Add(download);
                            cnt++;
                        }
                    }
                    if (filelist.Count() % 100 != 0)
                    {
                        imagePath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Images"), string.Format("{0}-{1}.zip", DateTime.Now.ToString("yyyyMMddHHmmssffff"), cnt));
                        ZipUtility.Zipfiles(filelist, imagePath);
                        download = Path.Combine(Request.ApplicationPath + "Images/", Path.GetFileName(imagePath));
                        downloadList.Add(download);
                    }
                    lastDownloadList = downloadList;
                    lastSerachList = listR;                    
                }
                else if (listR.Count() > 500)
                {
                    return Json(new { total = -1, info = "数据量过大，无法下载，请缩小检索条件或联系系统管理员" });
                }
                return Json(new { total = cnt, info = downloadList });
            }            
            else
            {
                listR = null;
                return Json(new { total = 0, info = "检索结果为空" });
            }
        }

        public ActionResult GetDisk(int diskID)
        {
            ime.Configuration.LazyLoadingEnabled = false;
            var diskinfo = ime.DiskInfo.Find(diskID).DiskLabel;
            return Json(new { info = diskinfo }, JsonRequestBehavior.AllowGet);
        }
        private void ImageList(List<ImageInfo> imagelist)
        {
            string tmpPath = System.Web.HttpContext.Current.Server.MapPath("~/Images");
            if (!Directory.Exists(tmpPath))
                Directory.CreateDirectory(tmpPath);
            try
            {
                for (int i = 0; i < imagelist.Count(); i++)
                {
                    if (System.IO.File.Exists(imagelist[i].ImagePath))
                    {
                        string filename = Path.GetFileName(imagelist[i].ImagePath);
                        string target = Path.Combine(tmpPath, filename);
                        if (!System.IO.File.Exists(target))
                        {
                            System.IO.File.Copy(imagelist[i].ImagePath, target, true);
                            //这里在加做一个缩略图
                            string targetThumb = target.Insert(target.Length - 4, "_Thumb");
                            //string targetThumb = tmpPath +"//" + Path.GetFileNameWithoutExtension(target) + "_Thumb" + Path.GetExtension(target);
                            Common.Thumb.MakeThumbnail(target, targetThumb, 360, 200, "HW");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void DeleteImage(string path)
        {
            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }
        }

    }
}